/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package leastsquaresapproximation;

import java.util.ArrayList;
import javax.swing.JFrame;

/**
 *
 * @author PavelsKletnojs
 */
public class Main {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
	try{
	    ReadFile rf = new ReadFile();
	    ArrayList<Double> x = rf.matrixAsList.get(0);
	    ArrayList<Double> y = rf.matrixAsList.get(1);
	    GaussianElimination ge;

/*	    
	    // Cheat for interpolation, where you must not to
	    // calculate Vandermonde matrix.
	     
	    ArrayList<ArrayList<Double>> matrix;
	    matrix = new ArrayList<ArrayList<Double>>();
	    //Create matrix
	    for(int j = 0; j<x.size(); j++){
		matrix.add(new ArrayList<Double>());
		for(int i = 0; i<x.size(); i++){
		    matrix.get(j).add(Math.pow(x.get(j),i));
		}
	    }
	    
	    //Append y to matrix
	    for(int i = 0; i<x.size(); i++){
		matrix.get(i).add(y.get(i));
	    }
	    
	    new GaussianElimination(matrix);
	    System.out.println("Matrix to calculate:");
	    ge.printMatrix();
	    
	    ge.runGaussianElimination(false);
	    
	    ge.printResultVector();
//*/	    
	    // Claculate polynomials for approximation
	    // *I know that Vandermonde matrix generates in each iteration, don't care.
	    ArrayList<ArrayList<Double>> polynoms = new ArrayList<ArrayList<Double>>();
	    for(int k = x.size()-1; k>=0; k--){
		//Create vandermonde matrix
		VandermondeMatrix vm = new VandermondeMatrix();
		vm.createVandermondeMatrix(x,k);
		vm.appendMatrixWithY(x, y, k);
		
		if (x.size()-1 == k){
		    System.out.println("Vandermonde matrix:");
		    vm.printMatrix();
		}

		ge = new GaussianElimination(vm.getMatrix());
		ge.runGaussianElimination(false);

		System.out.println();
		System.out.println("Result polynomial: (k = " + k + ")");
		ArrayList<Double> result = ge.getResultPoly();
		polynoms.add(result);
		
		for(Double d : result){
		    System.out.print(d + "\t");
		}
		System.out.println();
	    
	    }
	    
	    // Show plot in frame
	    JFrame f = new JFrame(); 
	    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	    Plotter plotter = new Plotter(x,y,polynoms);
	    f.add(plotter); 
	    f.setSize(600,600); 
	    f.setLocation(200,100); 
	    f.setVisible(true); 
//*/
	}
	catch(Exception e){
	    System.out.println(e);
	}
    }
}
